package cn.yl.fxboot.application.service.ffmpeg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FFmpegCommand {
	
	private List<String> command;
	
	public FFmpegCommand(List<String> command) {
		this.command = command == null ? new ArrayList<String>() : command;
	}
	
	public List<String> getCommand(){
		return command;
	}

	public void setCommand(List<String> command) {
		this.command = command;
	}
	
	public void start(FFmpegCallback<?> callback) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		ProcessBuilder processBuilder = new ProcessBuilder(command);
		processBuilder.redirectErrorStream(true);
		try {
			Process process = processBuilder.start();
			String line = null;
			br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			while((line=br.readLine()) != null) {
				sb.append(line);
				if(callback != null) {
					callback.processStream(line);
				}
			}
			
			int exitVal = process.waitFor();
			if(exitVal == 0 && callback != null) {
				callback.complete(sb.toString());
			}
			process.destroy();
		} catch (IOException e) {
			if(callback != null) {
				callback.error(e.getMessage());
			}
			e.printStackTrace();
		} catch (InterruptedException e) {
			if(callback != null) {
				callback.error(e.getMessage());
			}
			e.printStackTrace();
		} finally {
			if(br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
